package com.atguigu.user.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.springboot.springbootlogindemo.DTO.UserDTO;
import com.springboot.springbootlogindemo.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public RefreshTokenInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //假如还未登录，那么就没有token，ThreadLocal也不会保存信息，返回401
    //如果已经登录，但是token过期了，ThreadLocal有信息，

    //如果已经登录，且token没有过期，

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token = request.getHeader("Authorization");

        //如果token是空，直接就跳过拦截器，让下一个登录拦截器判断是否登录
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //通过token获取用户信息
        String key = "login:token:" + token;

        //因为前面存的userMap是用redisTemplate存的
        Map<Object, Object> userMap = redisTemplate.opsForHash().entries(key);

        //如果获取不到，可能是token已经失效，不管，还是让后面来判断
        if (userMap == null) {
            return true;
        }

        //那么有用户，也就是在登录状态,添加进连接池，那么下一个拦截器就不会拦截了
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);

        //重置token时间
        redisTemplate.expire(key, 30L, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}